var typeid = 0
var updateType = 0;
var message;
var thil;
var goodsSave;


$("#dcName").change(function () {
    amtWayChange(1);
})

function amtWayChange(type) { //页面加载 使发货仓没有的运送方式隐藏
    var warehouseCode = $('#dcName option:selected').val();
    var zywl = document.getElementsByName("amtWay");
    var express = document.getElementsByName("expressCheck");

    $.ajax({
        url: 'https://'+ window.location.host +'/api/admin/alogistics/getDispatchModeByWarehousecode.jhtml',
        //url: 'https://'+ window.location.host +'/api/admin/alogistics',
        cache: false, //禁用缓存
        type: "POST",
        dataType:"json",
        data:{warehouseCode:warehouseCode},
        success: function(obj){
            if (type==1){
                $("input[name='priceWay']").prop("checked",false);
            }
            zywl[0].style.display = "none";
            zywl[1].style.display = "none";
            express[0].style.display = "none";
            express[1].style.display = "none";
            zywl[1].style.display = "none";
            zywl[2].style.display = "none";
            zywl[3].style.display = "none";

            var typeWayList = obj.data;
            typeWayList = typeWayList.sort();
            if(typeWayList.length == 0){
                document.getElementById("carWay").style.display = "none";
                document.getElementById("amtWay").style.display = "none";
                document.getElementById("weightWay").style.display = "none";
                document.getElementById("volumeWeightWay").style.display = "none";
            }
            for(var i=0;i<typeWayList.length;i++){
                if (typeWayList[i] == 30){
                    zywl[3].style.display = "inline-block";
                    document.getElementById("carWay").style.display = "block";
                    document.getElementById("amtWay").style.display = "none";
                    document.getElementById("weightWay").style.display = "none";
                    document.getElementById("volumeWeightWay").style.display = "none";
                }
                if (typeWayList[i] == 10){
                    zywl[1].style.display = "inline-block";
                    express[0].style.display = "inline-block";
                    document.getElementById("carWay").style.display = "none";
                    document.getElementById("amtWay").style.display = "none";
                    document.getElementById("weightWay").style.display = "block";
                    document.getElementById("kuaiyun").style.display = "none";
                    document.getElementById("kuaidi").style.display = "block";
                    document.getElementById("volumeWeightWay").style.display = "none";
                }
                if (typeWayList[i] == 20){
                    express[1].style.display = "inline-block";
                    zywl[2].style.display = "inline-block";
                    document.getElementById("carWay").style.display = "none";
                    document.getElementById("amtWay").style.display = "none";
                    document.getElementById("weightWay").style.display = "none";
                    document.getElementById("volumeWeightWay").style.display = "block";
                    document.getElementById("kuaidi").style.display = "none";
                    document.getElementById("kuaiyun").style.display = "block";
                }
                if (typeWayList[i] == 40){
                    zywl[0].style.display = "inline-block";
                    document.getElementById("carWay").style.display = "none";
                    document.getElementById("amtWay").style.display = "block";
                    document.getElementById("weightWay").style.display = "none";
                    document.getElementById("volumeWeightWay").style.display = "none";
                }

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function amtDiv(thls,id) {
    if(id==1){
        if(thls.checked ==false){
            layer.msg('取消了按金额的计价方式', {icon: 7,time:2000,offset:[200,400]});
        }
        document.getElementById("carWay").style.display = "none";
        document.getElementById("weightWay").style.display = "none";
        document.getElementById("amtWay").style.display = "block";
        document.getElementById("volumeWeightWay").style.display = "none";
    }else if(id==2){
        if(thls.checked ==false){
            layer.msg('取消了按重量的计价方式', {icon: 7,time:2000,offset:[200,400]});
        }
        document.getElementById("carWay").style.display = "none";
        document.getElementById("amtWay").style.display = "none";
        document.getElementById("weightWay").style.display = "block";
        document.getElementById("volumeWeightWay").style.display = "none";
        document.getElementById("kuaiyun").style.display = "none";
        document.getElementById("kuaidi").style.display = "block";
    }else if(id==3){
        if(thls.checked ==false){
            layer.msg('取消了按车型的计价方式', {icon: 7,time:2000,offset:[200,400]});
        }
        document.getElementById("weightWay").style.display = "none";
        document.getElementById("amtWay").style.display = "none";
        document.getElementById("carWay").style.display = "block";
        document.getElementById("volumeWeightWay").style.display = "none";
    }else if (id == 4){
        if(thls.checked ==false){
            layer.msg('取消了按(体积/重量)的计价方式', {icon: 7,time:2000,offset:[200,400]});
        }
        document.getElementById("carWay").style.display = "none";
        document.getElementById("amtWay").style.display = "none";
        document.getElementById("weightWay").style.display = "none";
        document.getElementById("volumeWeightWay").style.display = "block";
        document.getElementById("kuaiyun").style.display = "block";
        document.getElementById("kuaidi").style.display = "none";
    }

}
/*
function expressClick(id) {
    if(id==1){
       ///////////////
    }else if(id==2){
        document.getElementById("kuaidi").style.display = "none";
        document.getElementById("kuaiyun").style.display = "block";
    }
}*/


function getAllWare2() {
    var sel = document.getElementById("dcName"); //页面发货仓下拉框数据
    $.ajax({
        url: 'https://'+ window.location.host +'/api/admin/abaseservice/area/getAllWarehouse',
        //url: 'https://'+ window.location.host +'/api/admin/alogistics',
        cache: false, //禁用缓存
        type: "POST",
        dataType:"json",
        data:{},
        success: function(obj){
            for(var i=0;i<obj.data.length;i++){
                var option = new Option(obj.data[i].warehouse_name,obj.data[i].warehouse_code);
                sel.options.add(option)
            }
            amtWayChange(2);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function DataInUp(){ //金额添加默认运费
    if(document.getElementById("costAmt").value == "" || document.getElementById("costPrice").value == ""){
        layer.msg('不能为空', {icon: 5,time:2000});
        return;
    }
    $("#goodsAmt").hide();
    $("#saveGoods").hide();
    var costAmt = document.getElementById("costAmt").value;
    var costPrice = document.getElementById("costPrice").value;
    var amtTable = document.getElementById("amtTableBody");
    var tableCostName= $(amtTable).children().find('.costName');
    for(var i=0;i<tableCostName.length;i++){
        if(costAmt == $(tableCostName[i]).text()){
            layer.msg('金额重复', {icon: 5,time:2000});
            return;
        }
    }
    $("#costAmt").val("");
    $("#costPrice").val("");
    $('#amtTableBody').append('<tr class="idcans" name="moneyName">' +
        '<td name="costAmtName" class="costName">'+costAmt+'</td><td name="costPriceName" class="costPrice">'+costPrice+'</td><td name="goodsNamePrice" class="costGoods"><a onclick="setting(this)">设置</a>' +
        '<input type="hidden" class="goodsId" name="goodsId"><input type="hidden" class="goodsName" name="goodsName"><input type="hidden" class="goodsPrice" name="goodsPrice"><input type="hidden" class="goodsAmt" name="goodsAmt"></td>' +
        '<td><a onclick="deleteTr(this)">删除</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick="updateTr(this,1)">修改</a></td></tr>');

}

function setting(thilt){ //点击设置  设置一级分类
    goodsSave = thilt;
    $("#trOne").nextAll().remove();
    var allInput = $(thilt).parent();
    var goodId = $(allInput).find('.goodsId').val();
    var goodName = $(allInput).find('.goodsName').val();
    var goodPrice = $(allInput).find('.goodsPrice').val();

    if(goodId == ""){

    }else{
        var goodIdList = goodId.split(",");
        var goodNameList = goodName.split(",");
        var goodPriceList = goodPrice.split(",");
        if (goodIdList[goodIdList.length-1] == "") {
            goodIdList.splice(goodIdList.length-1,1)
        }
        for(var i=0;i<goodIdList.length;i++) {
                $('#amtTableDown').append('<tr class="idcans"><td><span name="amtGoodsName" id="' + goodIdList[i] + '">' + goodNameList[i] + '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
                    '<a onclick="amount_update(this,2)" style="float: right">编辑</a></td>' +
                    '<td><input type="text" name="amtGoodsPrice" value="' + goodPriceList[i] + '" class="w-60 input-text radius mr-5 ml-5 text-c" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}\.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
                    '<td><a onclick="deleteTr(this)">删除</a></td></tr>')
        }
    }
 $("#goodsAmt").show();
 $("#saveGoods").show();
}


function saveGoodsAmt() { //保存选中的一级类目
    var goodsName = $("[name='amtGoodsName']");
    var goodsPrice = $("[name='amtGoodsPrice']");
    var id = "";
    var name = "";
    var price = "";
    var amtAllPrice = 0;
    for(var i=0;i<goodsName.length;i++){
        if(goodsName[i].id == "" || goodsPrice[i].value == ""){
            layer.msg('不能为空', {icon: 5,time:2000});
            return;
        }
        id += goodsName[i].id+",";
        name += $(goodsName[i]).text()+",";
        price += goodsPrice[i].value+",";
        amtAllPrice += Number(goodsPrice[i].value);
    }
    $($(goodsSave).nextAll()[0]).val(id);
    $($(goodsSave).nextAll()[1]).val(name);
    $($(goodsSave).nextAll()[2]).val(price);
    $($(goodsSave).nextAll()[3]).val(amtAllPrice);
    $("#goodsAmt").hide();
    $("#saveGoods").hide();
}

var dataUpdate = "";

function updateTr(thil,type) { //修改当前行内容
    dataUpdate = thil;
    if(type == 1) { //修改按金额列表数据
        $("#amt").val($($(thil).parent().prevAll()[2]).text());
        $("#price").val($($(thil).parent().prevAll()[1]).text());
        $("#price-update").modal("show");
        $(".addressTitle").html("修改金额信息");
    }
    if(type == 2){ //修改按车型列表数据
        $("#long").val($($(thil).parent().prevAll()[4]).text());
        $("#weight").val($($(thil).parent().prevAll()[3]).text());
        $("#maxVolume").val($($(thil).parent().prevAll()[2]).text());
        $("#amtCar").val($($(thil).parent().prevAll()[1]).text());
        $("#date").val($($(thil).parent().prevAll()[0]).text());
        $("#car-update").modal("show");
        $(".addressTitle").html("修改车型信息");

    }
}

function saveData(type) {  //保存 列表一条修改后的数据
    if (type == 1){ //修改按金额列表数据

        if($("#amt").val() == "" || $("#price").val() == "" ){
            layer.msg('不能为空', {icon: 5,time:2000});
            return;
        }

        var amt  = $("#amt").val();
        var price  = $("#price").val();
        $($(dataUpdate).parent().prevAll()[2]).text(amt);
        $($(dataUpdate).parent().prevAll()[1]).text(price);
        $("#price-update").modal("hide");
    }
    if(type == 2){ //修改按车型列表数据

        if($("#long").val() == "" || $("#weight").val() == "" || $("#maxVolume").val() == ""  || $("#amtCar").val() == "" || $("#date").val() == "" ){
            layer.msg('不能为空', {icon: 5,time:2000});
            return;
        }
        var long = $("#long").val();
        var weight = $("#weight").val();
        var maxVolume = $("#maxVolume").val();
        var amtCar = $("#amtCar").val();
        var date = $("#date").val();
        $($(dataUpdate).parent().prevAll()[4]).text(long);
        $($(dataUpdate).parent().prevAll()[3]).text(weight);
        $($(dataUpdate).parent().prevAll()[2]).text(maxVolume);
        $($(dataUpdate).parent().prevAll()[1]).text(amtCar);
        $($(dataUpdate).parent().prevAll()[0]).text(date);
        $("#car-update").modal("show");
        $(".addressTitle").html("修改车型信息");
        $("#car-update").modal("hide");
    }
}


function deleteTr(thle) { //删除表格 记录
    layer.confirm('是否确定删除该条记录', {
        btn: ['确定','返回'] //按钮
    }, function(index,layero){
        $(thle).parent().parent().remove();
        layer.close(index);
    }, function(index,layero){
        layer.close(index);
    });

}


var result;
function serchRange1(id) { //覆盖范围查询
    var warehouseCode = $('#dcName option:selected').val();
    var cityname ="";
    $.ajax({
        url:'https://'+ window.location.host +'/api/admin/alogistics/getLogisticsDispatchScopeByInfo.jhtml',
        cache: false, //禁用缓存
        type: "POST",
        data:{
            "warehouseCode":warehouseCode,
            "transportModeType":id
        },
        success: function(obj){
            result = obj.data;
            if(result.length != 0){
                for(var i=0;i<result.length;i++){
                    var addressId = result[i].areaCode;
                    if (0 != addressId) {
                        cityname +=  result[i].areaName+'全境, '
                    }else {
                        cityname +=  result[i].areaName
                    }

                   /* if(result[i].child_address_library.length !=0){
                        cityname +=  result[i].name +'<a onclick="more('+addressId+')">  更多</a>'+',  ';
                    }else{
                        cityname +=  result[i].name+'全境, '
                    }*/
                }
                layer.confirm(cityname, {
                    btn: ['返回'] //按钮
                }, function(index,layero){
                    layer.close(index);
                    //确定执行方法
                });
            }else{
                layer.confirm('暂无数据', {
                    btn: ['返回'] //按钮
                }, function(index,layero){
                    layer.close(index);
                    //确定执行方法
                });

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });

}


/*function more(addressId) {
    var allName = "";
    for(var i=0;i<result.length;i++){
        if (addressId == result[i].address_id){
            allName = result[i].child_address_library;
        }
    }
    if(allName.length != 0){
        var name = "";
        for(var j=0;j<allName.length;j++){
            name += allName[j].name+"  ,";
        }
        layer.confirm(name, {
            btn: ['返回'] //按钮
        }, function(index,layero){
            layer.close(index);
            //确定执行方法
        });
    }else{
        layer.confirm('暂无数据', {
            btn: ['返回'] //按钮
        }, function(index,layero){
            layer.close(index);
            //确定执行方法
        });
    }

}*/

function saveChecked() { //点击添加  将选中的一级分类加入其中
    var goodid = $("input:radio[name='classification01']:checked").next().text();
    goodid = goodid.replace(/\s+/g, "");
    var goodname = $("input:radio[name='classification01']:checked").next().children().val();
    if (goodid == ""){
        close_model();
    }else{
        if(typeid == 1){
            var name = $(message).parent().children()[0];
            $(name).html(goodname);
            $(name).attr('id',goodid);
            typeid = 0;
        }else{
            var els =document.getElementsByName("amtGoodsName");
            for (var i = 0, j = els.length; i < j; i++){
                if(goodname == els[i].innerText){
                    layer.msg('请勿选择重复的一级分类', {icon: 5,time:2000});
                    close_model();
                    return;
                }
            }
            $('#amtTableDown').append('<tr class="idcans"><td><span name="amtGoodsName" id="'+goodid+'">'+goodname+'</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
                '<a onclick="amount_update(this,2)" style="float: right">编辑</a></td>' +
                '<td><input type="text" name="amtGoodsPrice"class="w-60 input-text radius mr-5 ml-5 text-c" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}\.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
                '<td><a onclick="deleteTr(this)">删除</a></td></tr>')
        }
    }
    close_model();
}

function amount_update(thil,id){ //对已经加入的以及分类进行编辑
    typeid = 1;
    message = thil;
    $("#amount-add").modal("show");
    $(".addressTitle").html("编辑商品信息");
}




function dataInUpCar(){//车型 添加默认运费
    if(document.getElementById("carLong").value == "" || document.getElementById("carWeight").value == "" || document.getElementById("carAmt").value == "" || document.getElementById("carDate").value == "" || document.getElementById("carMaxVolume").value == ""){
        layer.msg('不能为空', {icon: 5,time:2000});
        return;
    }
    var carLong=document.getElementById("carLong").value;
    var carWeight=document.getElementById("carWeight").value;
    var carAmt=document.getElementById("carAmt").value;
    var carDate=document.getElementById("carDate").value;
    var carMaxVolume=document.getElementById("carMaxVolume").value;

    var carTable = document.getElementById("carTableUp");
    var tableCarLong= $(carTable).children().find('.carLong');
    for(var i=0;i<tableCarLong.length;i++){
        if(carLong == $(tableCarLong[i]).text()){
            layer.msg('车长重复', {icon: 5,time:2000});
            return;
        }
    }

    $("#carLong").val("");
    $("#carWeight").val("");
    $("#carMaxVolume").val("");
    $("#carAmt").val("");
    $("#carDate").val("");
    $('#carTableUp').append('<tr class="idcans" name="carUp">' +
        '<td class="carLong">'+carLong+'</td><td class="carWeight">'+carWeight+'</td><td class="carMaxVolume">'+carMaxVolume+'</td><td class="carAmt">'+carAmt+'</td><td class="carDate">'+carDate+'</td>' +
        '<td><a onclick="deleteTr(this)">删除</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick="updateTr(this,2)">修改</a></td></tr>');

}


function weightByArea(type){ //重量 快递 指定区域设置运费
    var warehouse = $('#dcName option:selected').text();
    var warehouseid=0;
    if(type ==1) {
        $('#weightTableDown').append('<tr class="idcans" name="weightDown">' +
            '<td>' + warehouse + '</td><td><span class="weightsName" id="">未添加区域</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
            '<a onclick="address_edit(this,1)" style="float: right">编辑</a></td>' +
            '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c wfirstWeight" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
            '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c wfirstPrice" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
            '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c wlastWeight" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
            '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c wlastPrice" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
            '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c waging" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
            '<td><a onclick="deleteTr(this)">删除</a></td></tr>')
    }
}


function volumeWeightByArea() {
    //快递 指定区域设置运费
    var warehouse = $('#dcName option:selected').text();
    var warehouseid=0;
    $('#volumeWeightTableDownYun').append('<tr class="idcans" name="weightDownYun">' +
        '<td>' + warehouse + '</td><td><span class="weightsNameYun" id="">未添加区域</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
        '<a onclick="address_edit(this,2)" style="float: right">编辑</a></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c startFreight" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c yuanCube" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c yuanKilogram" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c yuanTon" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c sendFreight" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c trunkLinePrescription" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c sendPrescription" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><a onclick="deleteTr(this)">删除</a></td></tr>')

}





function carByArea(){ //车型 指定区域设置运费
    var warehouse = $('#dcName option:selected').text();

    var trList = $("#carTableDown").children();
    var warehouseid = trList.length;

    $('#carTableDown').append('<tr class="idcans" id="'+warehouseid+'" name="carDown">' +
        '<td>'+warehouse+'</td><td><span class="carsName" id="">未添加区域</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
        '<a onclick="address_edit(this,3)" style="float: right">编辑</a></td>' +
        '<td><input type="text" maxlength="9" onblur="inValue(this)"  class="w-60 input-text radius mr-5 ml-5 text-c carLongDown" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c carWeightDown" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c carMaxVolumeDown" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c carAmtDown" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><input type="text" maxlength="9" class="w-60 input-text radius mr-5 ml-5 text-c carDateDown" onkeyup="(this.v=function(){this.value=this.value.replace(/[^\\d{1,}.\\d{1,}|\\d{1,}]/g,\'\');}).call(this)" onblur="this.v();"></td>' +
        '<td><a onclick="deleteTr(this)">删除</a></td></tr>');
}


function inValue(tell) {
    var value = tell.value;
    var spanCity = $(tell).parent().prev().children()[0];
    var trList = $("#carTableDown").children();

    var trid = $(tell).parent().parent();

    if(trList.length > 1){
        var spanId;
        if(spanCity.id != null){
            var spanIdList = spanCity.id.split(",")
            spanId = spanIdList[spanIdList.length-1];
        }
       for (var i=0;i<trList.length;i++){
           var trOne  = trList[i];
           if($(trOne)[0].id == trid[0].id){
               trList.splice(i,1);
           }
        }
        for (var i=0;i<trList.length;i++){
            var city = $(trList[i]).find('.carsName');
            var carLong = $(trList[i]).find('.carLongDown');
            var cityList = city[0].id.split(",");
            if(spanId == cityList[cityList.length-1]){
                if(value == $(carLong).val()){
                    layer.msg('目的地重复,不可输入重复的车长', {icon: 5,time:2000});
                    $(tell).val("")
                }
            }
        }
    }
}


function address_edit(thile,id) { //修改地址
    thil = thile;
    updateType = id;
    $("#address-edit").modal("show");
    $(".addressTitle").html("修改地址信息");
}





function saveCity() { //保存 选中的地址
    var cityName= $("#vueProvinceName").text()+" "+$("#vueCityName").text()+" "+$("#vueCountyName").text()+" "+$("#vueVillageName").text();
    var goodId = "";
    if($("#provinceId").text() != null){
        goodId = $("#provinceId").text()
    }
    if($("#cityId").text() != ""){
        goodId = goodId +","+$("#cityId").text()
    }
    if($("#countyId").text() != ""){
        goodId = goodId +","+$("#countyId").text()
    }
    if($("#villageId").text() != ""){
        goodId = goodId +","+$("#villageId").text()
    }
    if(goodId == ""){
        layer.msg('未选择地区', {icon: 5,time:2000});
    }
    if(updateType == 1){
        var goodsIdList = goodId.split(",");
        var weightList = $("#weightTableDown").children();
       if (weightList.length > 1){
            for (var i=0;i<weightList.length;i++){
                var cityId = $(weightList[i]).find('.weightsName');
                var cityIdList = cityId[0].id.split(",");
                if(goodsIdList[goodsIdList.length-1] == cityIdList[cityIdList.length-1]){
                    layer.msg('目的地重复', {icon: 5,time:2000});
                    return;
                }
            }
        }
    }else if(updateType == 2){
        var goodsIdList = goodId.split(",");
        var weightList = $("#volumeWeightTableDownYun").children();
        if (weightList.length > 1){
            for (var i=0;i<weightList.length;i++){
                var cityId = $(weightList[i]).find('.weightsNameYun');
                var cityIdList = cityId[0].id.split(",");
                if(goodsIdList[goodsIdList.length-1] == cityIdList[cityIdList.length-1]){
                    layer.msg('目的地重复', {icon: 5,time:2000});
                    return;
                }
            }
        }
    }else if(updateType == 3){
        var input = $(thil).parent().next().children()[0];
        var inputValue = $(input).val();
        var goodsIdList = goodId.split(",");
        if(inputValue != ""){
            var carList = $("#carTableDown").children();
            var trid = $(thil).parent().parent();
            for (var i=0;i<carList.length;i++){
                var trOne  = carList[i];
                if($(trOne)[0].id == trid[0].id){
                    carList.splice(i,1);
                }
            }
            for (var i=0;i<carList.length;i++){
                var city = $(carList[i]).find('.carsName');
                var carLong = $(carList[i]).find('.carLongDown');
                var cityList = city[0].id.split(",");
                    if(inputValue == $(carLong).val()){
                        if(goodsIdList[goodsIdList.length-1] == cityList[cityList.length-1]){
                            layer.msg('重复的车长,不能选择重复的目的地', {icon: 5,time:2000});
                            return;
                        }
                    }
            }
        }
    }

    var name = $(thil).parent().children()[0];
    $(name).html(cityName);
    $(name).attr('id',goodId);
    $("#address-edit").modal("hide");
}


$("#coupon-add").validate({
    rules: {
        inputName:{
            required: true,//是否是必填项
        }
    },
    submitHandler:function(form){
        saveTemplate();
    }
})



function saveTemplate() {  //新增运费模板

    var freightTemplate = "";
    var loginData=JSON.parse(web.readCookie("loginData"));

    var warehouseCode = $('#dcName option:selected').val(); //发货仓code
    var warehouseName = $('#dcName option:selected').text(); //发货仓名称
    var templateName = $("#templateName").val(); //模板名称
    var valuationType = ""; // 计算价格方式
    var status = 20; //状态

    var createUser = loginData.user.name; //创建人
    var transportModeType = ""; //运送方式

    var moneyRoles = []; //按金额规则集合
    var weightRoles = []; //按重量规则集合
    var carRoles = []; //按车型规则集合
    var kyRoles = []; //按体积/重量规则集合

    obj = document.getElementsByName("priceWay");
    var checkboxvalue = [];
    for(t in obj){
        if(obj[t].checked){
            checkboxvalue.push(obj[t].value);
        }
    }
    if (checkboxvalue.length == 0){
        //影藏等待样式
        $("#beijing").css("display","none");
        $("#myLoading").css("display","none");
        layer.msg('必须选择一种计价方式', {icon: 5,time:2000});
        return;
    }

    for(t in obj){
        if(obj[t].checked){
            if(obj[t].value == 10) { //金额模板
                valuationType += obj[t].value +","; //添加计价方式
                var zywlValue = [];
                zywl = document.getElementsByName("xfsLogistics"); //鑫方盛物流
                for(q in zywl){
                    if(zywl[q].checked){
                        zywlValue.push(zywl[q].value);
                        transportModeType += zywl[q].value +",";
                    }
                }
                if(zywlValue.length == 0){
                    //影藏等待样式
                    $("#beijing").css("display","none");
                    $("#myLoading").css("display","none");
                    layer.msg('必须选择自有物流的运送方式', {icon: 5,time:2000});
                    return;
                }
                var trels = document.getElementsByName("moneyName");
                if(trels.length == 0){
                    //影藏等待样式
                    $("#beijing").css("display","none");
                    $("#myLoading").css("display","none");
                    layer.msg('请填写默认金额运费内容', {icon: 5,time:2000});
                    return;
                }
                for (var i = 0; i < trels.length; i++) {
                    var dataMoney = "";
                    var tdelser = $(trels)[i];
                    var moneyDefaultFreight = $(tdelser).find('.costName').text();
                    var moneyFreight = $(tdelser).find('.costPrice').text();
                    var moneyCategoryId = $(tdelser).find('.goodsId').val();
                    var moneyCategoryName = $(tdelser).find('.goodsName').val();
                    var moneyCategoryFreight = $(tdelser).find('.goodsPrice').val();
                    var moneyAddFreight = $(tdelser).find('.goodsAmt').val();

                    dataMoney = {"moneyDefaultFreight": moneyDefaultFreight, "moneyFreight": moneyFreight, "moneyCategoryName": moneyCategoryName,
                        "moneyCategoryId": moneyCategoryId, "moneyAddFreight": moneyAddFreight,"moneyCategoryFreight":moneyCategoryFreight
                    };
                    moneyRoles.push(dataMoney);
                }
            }
            if(obj[t].value == 20) {  //重量模板
                valuationType += obj[t].value +","; //添加计价方式
                kdky = document.getElementsByName("express"); //快递快运
                var kdkyvalue = [];
                for(t in kdky){
                    if(kdky[t].checked){
                        kdkyvalue.push(kdky[t].value);
                    }
                }
                if (kdkyvalue.length == 0){
                    //影藏等待样式
                    $("#beijing").css("display","none");
                    $("#myLoading").css("display","none");
                    layer.msg('必须选择物流运送方式', {icon: 5,time:2000});
                    return;
                }
                for(w in kdky){
                    if(kdky[w].checked){
                        if(kdky[w].value ==10){
                            if($("#firstWeight").val() == "" || $("#firstPrice").val()  =="" || $("#weightAdd").val()==""|| $("#priceAdd").val()=="" || $("#time").val() == ""){
                                //影藏等待样式
                                $("#beijing").css("display","none");
                                $("#myLoading").css("display","none");
                                layer.msg('默认快递运费不能为空 无法提交', {icon: 5,time:2000});
                                return;
                            }
                            var dataWeight = "";  //快递数据
                            var firstWeight = $("#firstWeight").val();
                            var firstPrice = $("#firstPrice").val();
                            var weightAdd = $("#weightAdd").val();
                            var priceAdd = $("#priceAdd").val();
                            var time = $("#time").val();
                            var weightIsDefault = 10;
                            var weightAreaCode = "";
                            var weightAreaName = "";
                            var belongMode = 10;
                            dataWeight = {"weightFirstWeight": firstWeight,"weightFirstMoney": firstPrice,"weightAddWeight": weightAdd,
                                "weightAddMoney": priceAdd,"weightPrescription":time,"weightIsDefault": weightIsDefault,"weightAreaCode": weightAreaCode,"weightAreaName": weightAreaName,"belongMode":belongMode};
                            weightRoles.push(dataWeight);
                            var trweight = document.getElementsByName("weightDown");
                            for (var i = 0; i < trweight.length; i++) {
                                var dataWeightd = "";
                                var tdweight = $(trweight)[i];
                                var firstWeightd = $(tdweight).find('.wfirstWeight').val();
                                var firstPriced = $(tdweight).find('.wfirstPrice').val();
                                var weightAddd = $(tdweight).find('.wlastWeight').val();
                                var priceAddd = $(tdweight).find('.wlastPrice').val();
                                var timed = $(tdweight).find('.waging').val();
                                var weightIsDefaultd = 20;
                                var belongMode =10;
                                var weightAreaCoded = $(tdweight).find('.weightsName').attr("id");
                                var weightAreaNamed = $(tdweight).find('.weightsName').text();
                                if(firstWeightd == "" || firstPriced  =="" || weightAddd ==""|| priceAddd =="" || timed =="" || weightAreaCoded  == "" || weightAreaNamed == ""){
                                    layer.msg('快递重量指定区域存在空值 无法提交', {icon: 5,time:2000});
                                    return;
                                }
                                dataWeightd = {"weightFirstWeight":firstWeightd,"weightFirstMoney": firstPriced,"weightAddWeight": weightAddd,"weightAddMoney": priceAddd,
                                    "weightPrescription": timed,"weightIsDefault": weightIsDefaultd,"weightAreaCode": weightAreaCoded,"weightAreaName": weightAreaNamed,"belongMode":belongMode};
                                weightRoles.push(dataWeightd);
                            }
                        }
                        transportModeType += kdky[w].value +",";
                        }

                    }
                }

            if(obj[t].value == 30){ //车型运费取值
                valuationType += obj[t].value +",";//添加计价方式
                var zcbcValue = [];
                zcbc = document.getElementsByName("chartered"); //专车包车
                for(e in zcbc){
                    if(zcbc[e].checked){
                        zcbcValue.push(zcbc[e].value);
                        transportModeType += zcbc[e].value +",";
                    }
                }
                if(zcbcValue.length  == 0){
                    //影藏等待样式
                    $("#beijing").css("display","none");
                    $("#myLoading").css("display","none");
                    layer.msg('必须选择按车型的物流运送方式', {icon: 5,time:2000});
                    return;
                }
                var trCarUp = document.getElementsByName("carUp");
                if(trCarUp.length  == 0){
                    //影藏等待样式
                    $("#beijing").css("display","none");
                    $("#myLoading").css("display","none");
                    layer.msg('必须填写按车型默认运费', {icon: 5,time:2000});
                    return;
                }
                for (var i = 0; i < trCarUp.length; i++) {
                    var dataCarUp = "";
                    var tdCarUp = $(trCarUp)[i];
                    var carLong = $(tdCarUp).find('.carLong').text();
                    var carWeight = $(tdCarUp).find('.carWeight').text();
                    var carMaxVolume = $(tdCarUp).find('.carMaxVolume').text();
                    var carAmt = $(tdCarUp).find('.carAmt').text();
                    var carDate = $(tdCarUp).find('.carDate').text();
                    var carIsDefault = 10;
                    var carAreaCode = "";
                    var carAreaName = "";
                    if(carLong == "" || carWeight  =="" || carAmt ==""|| carDate =="" || carMaxVolume == "" ){
                        layer.msg('默认车型运送方式存在空值 无法提交', {icon: 5,time:2000});
                        return;
                    }
                    dataCarUp = {"carLength":carLong,"carMaxLoad":carWeight,"carMaxVolume":carMaxVolume,"carFreight":carAmt,"carPrescription":carDate,
                        "carIsDefault":carIsDefault,"carAreaCode":carAreaCode,"carAreaName":carAreaName};
                    carRoles.push(dataCarUp);
                }
                var trCarDown = document.getElementsByName("carDown");
                for (var i = 0; i < trCarDown.length; i++) {
                    var dataCarDown = "";
                    var tdCarDown = $(trCarDown)[i];
                    var carLong = $(tdCarDown).find('.carLongDown').val();
                    var carWeight = $(tdCarDown).find('.carWeightDown').val();
                    var carMaxVolume = $(tdCarDown).find('.carMaxVolumeDown').val();
                    var carAmt = $(tdCarDown).find('.carAmtDown').val();
                    var carDate = $(tdCarDown).find('.carDateDown').val();
                    var carIsDefault = 20;
                    var carAreaCode = $(tdCarDown).find('.carsName').attr("id");
                    var carAreaName = $(tdCarDown).find('.carsName').text();
                    if(carLong == "" || carWeight  =="" || carAmt ==""|| carDate =="" || carAreaCode == "" || carAreaName == ""){
                        layer.msg('车型指定运送区域存在空值 无法提交', {icon: 5,time:2000});
                        return;
                    }
                    dataCarDown = {"carLength":carLong,"carMaxLoad":carWeight,"carMaxVolume":carMaxVolume,"carFreight":carAmt,"carPrescription":carDate,
                            "carIsDefault":carIsDefault,"carAreaCode":carAreaCode,"carAreaName":carAreaName};
                    carRoles.push(dataCarDown);
                }
            }



            if(obj[t].value == 40) {  //体积/重量模板
                valuationType += obj[t].value +","; //添加计价方式
                kdky = document.getElementsByName("express2"); //快递快运
                var kdkyvalue = [];
                for(t in kdky){
                    if(kdky[t].checked){
                        kdkyvalue.push(kdky[t].value);
                    }
                }
                if (kdkyvalue.length == 0){
                    //影藏等待样式
                    $("#beijing").css("display","none");
                    $("#myLoading").css("display","none");
                    layer.msg('必须选择物流运送方式', {icon: 5,time:2000});
                    return;
                }
                for(w in kdky){
                    if(kdky[w].checked){
                        if(kdky[w].value ==20) {
                            if ($("#startFreight").val() == "" || $("#yuanCube").val() == "" || $("#yuanKilogram").val() == "" || $("#yuanTon").val() == "" || $("#sendFreight").val() == "" || $("#trunkLinePrescription").val() == "" || $("#sendPrescription").val() == "") {
                                layer.msg('默认快运运费不能为空 无法提交', {icon: 5, time: 2000});
                                return;
                            }
                            var dataWeight = "";  //快运数据
                            var startFreight = $("#startFreight").val();
                            var yuanCube = $("#yuanCube").val();
                            var yuanKilogram = $("#yuanKilogram").val();
                            var yuanTon = $("#yuanTon").val();
                            var sendFreight = $("#sendFreight").val();
                            var trunkLinePrescription = $("#trunkLinePrescription").val();
                            var sendPrescription = $("#sendPrescription").val();
                            var kyIsDefault = 10;
                            var kyAreaCode = "";
                            var kyAreaName = "";
                            dataWeight = {
                                "startFreight": startFreight,
                                "yuanCube": yuanCube,
                                "yuanKilogram": yuanKilogram,
                                "yuanTon": yuanTon,
                                "sendFreight": sendFreight,
                                "trunkLinePrescription": trunkLinePrescription,
                                "sendPrescription": sendPrescription,
                                "kyIsDefault": kyIsDefault,
                                "kyAreaCode": kyAreaCode,
                                "kyAreaName": kyAreaName
                            };
                            kyRoles.push(dataWeight);
                            var trweight = document.getElementsByName("weightDownYun");
                            for (var i = 0; i < trweight.length; i++) {
                                var dataWeightd = "";
                                var tdweight = $(trweight)[i];
                                var startFreight = $(tdweight).find('.startFreight').val();
                                var yuanCube = $(tdweight).find('.yuanCube').val();
                                var yuanKilogram = $(tdweight).find('.yuanKilogram').val();
                                var yuanTon = $(tdweight).find('.yuanTon').val();
                                var sendFreight = $(tdweight).find('.sendFreight').val();
                                var trunkLinePrescription = $(tdweight).find('.trunkLinePrescription').val();
                                var sendPrescription = $(tdweight).find('.sendPrescription').val();
                                var kyIsDefault = 20;
                                var kyAreaCode = $(tdweight).find('.weightsNameYun').attr("id");
                                var kyAreaName = $(tdweight).find('.weightsNameYun').text();
                                if (startFreight == "" || yuanCube == "" || yuanKilogram == "" || yuanTon == "" || sendFreight == "" || trunkLinePrescription == "" || sendPrescription == "" || kyAreaCode == "" || kyAreaName == "") {
                                    layer.msg('快运重量指定区域存在空值 无法提交', {icon: 5, time: 2000});
                                    return;
                                }
                                dataWeightd = {
                                    "startFreight": startFreight,
                                    "yuanCube": yuanCube,
                                    "yuanKilogram": yuanKilogram,
                                    "yuanTon": yuanTon,
                                    "sendFreight": sendFreight,
                                    "trunkLinePrescription": trunkLinePrescription,
                                    "sendPrescription": sendPrescription,
                                    "kyIsDefault": kyIsDefault,
                                    "belongMode": belongMode,
                                    "kyAreaCode": kyAreaCode,
                                    "kyAreaName": kyAreaName
                                };
                                kyRoles.push(dataWeightd);
                            }
                        }

                        transportModeType += kdky[w].value +",";
                    }

                }
            }
        }
    }

console.log(transportModeType)
    var flag = true;
    var flag_msg ="";

    //判断运送方式的覆盖范围
    if (transportModeType.indexOf("40") != -1){
        //鑫方盛物流
        $.ajax({
            url:'https://'+ window.location.host +'/api/admin/alogistics/getLogisticsDispatchScopeByInfo.jhtml',
            //url: 'https://'+ window.location.host +'/api/admin/baseservice/area/getWarehouseCoverAddress',
            cache: false, //禁用缓存
            type: "POST",
            async:false,
            data:{
                "warehouseCode":warehouseCode,
                "transportModeType":"40"
            },
            success: function(obj){
                var datas = obj.data;
                if (null == datas || datas.length == 0){
                    layer.msg('鑫方盛物流没有覆盖范围,无法完成添加操作', {icon: 5,time:2000});
                    flag = false;
                    flag_msg = "鑫方盛物流没有覆盖范围,无法完成添加操作";
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    }
    if (transportModeType.indexOf("10") != -1){
        //快递
        $.ajax({
            url:'https://'+ window.location.host +'/api/admin/alogistics/getLogisticsDispatchScopeByInfo.jhtml',
            //url: 'https://'+ window.location.host +'/api/admin/baseservice/area/getWarehouseCoverAddress',
            cache: false, //禁用缓存
            type: "POST",
            async:false,
            data:{
                "warehouseCode":warehouseCode,
                "transportModeType":"10"
            },
            success: function(obj){
                var datas = obj.data;
                if (null == datas || datas.length == 0){
                    layer.msg('快递没有覆盖范围,无法完成添加操作', {icon: 5,time:2000});
                    flag = false;
                    flag_msg = "快递没有覆盖范围,无法完成添加操作";
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    }
    if (transportModeType.indexOf("20") != -1){
        //快运
        $.ajax({
            url:'https://'+ window.location.host +'/api/admin/alogistics/getLogisticsDispatchScopeByInfo.jhtml',
            //url: 'https://'+ window.location.host +'/api/admin/baseservice/area/getWarehouseCoverAddress',
            cache: false, //禁用缓存
            type: "POST",
            async:false,
            data:{
                "warehouseCode":warehouseCode,
                "transportModeType":"20"
            },
            success: function(obj){
                var datas = obj.data;
                if (null == datas || datas.length == 0){
                    layer.msg('快运没有覆盖范围,无法完成添加操作', {icon: 5,time:2000});
                    flag = false;
                    flag_msg = "快运没有覆盖范围,无法完成添加操作";
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    }
    if (transportModeType.indexOf("30") != -1){
        //专车包车
        $.ajax({
            url:'https://'+ window.location.host +'/api/admin/alogistics/getLogisticsDispatchScopeByInfo.jhtml',
            //url: 'https://'+ window.location.host +'/api/admin/baseservice/area/getWarehouseCoverAddress',
            cache: false, //禁用缓存
            type: "POST",
            async:false,
            data:{
                "warehouseCode":warehouseCode,
                "transportModeType":"30"
            },
            success: function(obj){
                var datas = obj.data;
                if (null == datas || datas.length == 0){
                    layer.msg('专车包车没有覆盖范围,无法完成添加操作', {icon: 5,time:2000});
                    flag = false;
                    flag_msg = "专车包车没有覆盖范围,无法完成添加操作";
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    }
    if (flag){
        freightTemplate = {'warehouseCode':warehouseCode,'warehouseName':warehouseName,
            'templateName':templateName,'valuationType':valuationType,'status':status,'createUser':createUser,'transportModeType':transportModeType};
        $.ajax({
            contentType: "application/json",
            url: 'https://'+ window.location.host +'/api/admin/alogistics/addFreightTemplate.jhtml',
            cache: false, //禁用缓存
            type: "POST",
            dataType: "json",
            data: JSON.stringify({
                "freightTemplate":freightTemplate,
                "moneyRoles":moneyRoles,
                "weightRoles":weightRoles,
                "carModeRoles":carRoles,
                "kyRoles":kyRoles
            }),
            success: function(result){
                //layer.msg(result.sub_msg, {icon: 1,time:2000});
                if (result.sub_code == 0){
                    layer.msg(result.sub_msg, {
                        icon: 1,
                        time: 1000,
                        end: function () {
                            var index =  parent.location.reload();
                            parent.layer.close(index);
                        }
                    });
                }else {
                    layer.msg(result.sub_msg, {icon: 5,time:2000});
                }


            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest);
                //alert(XMLHttpRequest);
            }
        });
    }else {
        layer.msg(flag_msg, {icon: 5,time:2000});
    }





}
function close_insert() {
    var index =  parent.location.reload();
    parent.layer.close(index);
}





